package com.xutong.myfunction.socket;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Created by hasee on 2016/11/24.
 */
public class UDPSocket {

    private static final String TAG = "UDPSocket";
    private static DatagramSocket datagramSocket = null;

    /**
     * 绑定本地地址和端口
     * @param localPort 本地端口
     * @return
     */
    public boolean bindPort(int localPort){

        if (datagramSocket==null){
            try {
                datagramSocket = new DatagramSocket(null);
                datagramSocket.setReuseAddress(true);
                datagramSocket.bind(new InetSocketAddress(localPort));
                return true;
            } catch (SocketException e) {
                e.printStackTrace();
                return false;
            }

        }
    return false;
    }

    /**
     * 接收数据
     * @return
     */
    public byte[] receiveSocketData(){
        byte[] data = new byte[4*1024];
        if (datagramSocket!=null){

            try {
                DatagramPacket datagramPacket = new DatagramPacket(data,data.length);
                Log.i(TAG,"服务器启动，等待接收数据");
                datagramSocket.receive(datagramPacket);
                Log.i(TAG,"接收到数据了");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    return data;
    }

    /**
     * 发送数据
     * @param targetAddress 目标地址
     * @param targetPort 目标端口
     * @param data 数据内容
     */
    public void sendSocketData(String targetAddress,int targetPort,String data){
        if (datagramSocket!=null){
            try {
                InetAddress inetAddress = InetAddress.getByName(targetAddress);

                byte[] sendData = data.getBytes();

                DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, inetAddress, targetPort);

                datagramSocket.send(datagramPacket);
                Log.i(TAG, "发送数据");
            }catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 关闭Socket
     */
    public void colseSocket(){

        if (datagramSocket!=null){
            datagramSocket.close();
            datagramSocket = null;//必须清空，否则重连后会无法使用：重复出现socket is closed
        }

    }


}
